﻿using HandyControl.Data;
using Microsoft.Win32;
using Model;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Input;
using System.Windows.Media;
using Util;
using MessageBox = HandyControl.Controls.MessageBox;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using WpfApp;
using System.Reflection;
using System.Drawing.Printing;
using System.Drawing;

namespace WpfApp1
{


    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public List<ExamInee> examIneeList = new List<ExamInee>();

        public Group groupData = new Group();


        /// <summary>
        /// 职位列表
        /// </summary>
        public List<Job> jobList = new List<Job>();

        /// <summary>
        /// 登录类
        /// </summary>
        public Login login;

        /// <summary>
        /// 岗位抽签时候每个职位的数量
        /// </summary>
        public Hashtable JobMumberHash = new Hashtable();

        public int errorRow = 0;

        public int ActualNumber = 0;

        public int TextIndex = 4;

        public String errorType = "";

        public string[] AllValidate = new string[] { "id","sort" };

        public string[] IdValidate = new string[] { "id"};

        public string lastText = "";

        public List<CategoryInfo> categoryList = new List<CategoryInfo>();


        public bool isUse = false;


        public bool fock = false;

        public string FileName = "";
        /// <summary>
        /// 最大序号 如果大于了最大序号就直接验证是否大于总人数
        /// </summary>
        public int maxNo = 99;

        public MainWindow()
        {
            InitializeComponent();

        }
        

        public MainWindow(List<ExamInee> examIneeList, Group groupData, List<Job> jobList, Login login)
        {
            InitializeComponent();
            this.examIneeList = examIneeList;
            this.groupData = groupData;
            this.jobList = jobList;

            this.login = login;
            //groupData.sort_method = "job";



            examIneeList = ExamIneeSort.buildCompany(this.jobList, this.examIneeList);


            this.total.Content = this.examIneeList.Count;

            this.dataGrid.ItemsSource = examIneeList;

            this.groupName.Content = groupData.name;

            this.examineeName.Text = groupData.Interview;



            if (groupData.sort_method == "group")
            {
                this.sortType.Content = "小组抽签";
            }
            else
            {
                this.sortType.Content = "岗位内抽签";

            }

            categoryList.Add(new CategoryInfo { Name = "正常", Value = "1"});
            categoryList.Add(new CategoryInfo { Name = "违纪", Value = "2"});
            categoryList.Add(new CategoryInfo { Name = "弃考", Value = "3"});
            
            foreach (ExamInee item in examIneeList)
            {
                item.comboxList = categoryList;
                item.result_text = "正常";
            }


            this.WindowState = WindowState.Maximized;
            ////SystemParameters.WorkArea.Heigh:得到屏幕工作区域高度
            ////SystemParameters.WorkArea.Width:得到屏幕工作区域宽度
            ////定义窗口最小高度与宽度
            this.MinHeight = this.MaxHeight = this.Height = SystemParameters.WorkArea.Height + 17;
            this.MaxWidth = this.MinWidth = this.Width = SystemParameters.WorkArea.Width + 17;


            //初始化打印机列表
            this.comboBox.ItemsSource = Print.PrintMedias();

           

            //获取默认打印机的方法
            PrintDocument fPrintDocument = new PrintDocument();

            comboBox.Text = fPrintDocument.PrinterSettings.PrinterName;

            //this.contextMenu.ItemsSource = Print.PrintMedias();
        }

        private void btnMenu_Click(object sender, RoutedEventArgs e)
        {
            Console.Write("123");

            //this.comboBox.            //this.comboBox.            //this.comboBox.
            //目标
            //this.contextMenu.PlacementTarget = this.btnMenu;
            ////位置
            //this.contextMenu.Placement = PlacementMode.Top;
            ////显示菜单
            //this.contextMenu.IsOpen = true;
        }


        private void imageBtnview_Initialized(object sender, EventArgs e)
        {
            //设置右键菜单为null 
            this.imageBtnview.ContextMenu = null;
        }


        private void imageBtnview_Click(object sender, RoutedEventArgs e)
        {
            ////显示菜单
            this.comboBox.IsDropDownOpen = true;
        }

        /// <summary>
        /// 导出按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click_Out(object sender, RoutedEventArgs e)
        { 
            //this.Actual.Focus();
            if (!CheckNumber(true,AllValidate))
            {
                //if (errorType == "actual")
                //{
                //    Actual.Focus();

                //    return;
                //}

                dataGrid.UnselectAll();


                DataGridRow row2 = dataGrid.ItemContainerGenerator.ContainerFromIndex(errorRow) as DataGridRow;


                row2.IsSelected = true;


                DataGridTemplateColumn tempColumn = this.dataGrid.Columns[TextIndex] as DataGridTemplateColumn;

                FrameworkElement element1 = this.dataGrid.Columns[TextIndex].GetCellContent(this.dataGrid.Items[errorRow]);
                TextBox ck1 = tempColumn.CellTemplate.FindName("textBoxNo", element1) as TextBox;
                ck1.Text = "";
                ck1.Focus();


                return;
            }


            DataGridViewToExcel(this.dataGrid);
        }

        /// <summary>
        /// 回车事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RepairItems_PreviewKeyDown(object sender, KeyEventArgs e)
        {
        
            Int32 row;

            DataGridRow row2;

            DataGridTemplateColumn tempColumn;

            FrameworkElement element;

            TextBox ck;
            try
            {
                if (e.Key != Key.Enter)
                {
                    return;
                }

                TextBox textBox = sender as TextBox;

                //字符串为空并且不能有错误
                if (String.IsNullOrWhiteSpace(textBox.Text) && !(CheckNumber(true, IdValidate)))
                {
                    return;
                }

                fock = true;

                e.Handled = true;


                if (CheckNumber(true,IdValidate))
                {

                    dataGrid.UnselectAll();

                    row = this.dataGrid.Items.IndexOf(this.dataGrid.CurrentItem);
                    row2 = dataGrid.ItemContainerGenerator.ContainerFromIndex(row + 1) as DataGridRow;

                    if (row2 == null)
                    {
                        return;
                    }

                    row2.IsSelected = true;


                    tempColumn = this.dataGrid.Columns[TextIndex] as DataGridTemplateColumn;



                    //然后获取DataGridTemplateColumn单元格元素
                    element = this.dataGrid.Columns[TextIndex].GetCellContent(this.dataGrid.Items[row + 1]);
                    ck = tempColumn.CellTemplate.FindName("textBoxNo", element) as TextBox;

                    ck.Focus();

                    return;
                }
                else
                {
                    //if (errorType == "actual")
                    //{
                    //    //Actual.Text = "";
                    //    //Actual.Focus();
                    //    return;
                    //}

                }



            }
            catch (Exception)
            {

            }
        }

        /// <summary>
        /// 失去焦点
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TextBoxNo_LostFocus(object sender, RoutedEventArgs e)
        {

            TextBox textBox = sender as TextBox;

            lastText = textBox.Text;

            if (String.IsNullOrWhiteSpace(textBox.Text) && !(CheckNumber(true, IdValidate)))
            {
                return;
            }

            fock = true;

        }


        /// <summary>
        /// 选择改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void DataGrid_SelectedCellsChanged(object sender, SelectedCellsChangedEventArgs e)
        {
            if (fock == false)
            {
                return;
            }

            fock = false;

            Int32 Col = this.dataGrid.Columns.IndexOf(this.dataGrid.CurrentColumn);
            
            if (!CheckNumber(true,IdValidate))
            {
                //if (errorType == "actual")
                //{
                //    //Actual.Text = "";
                //    Actual.Focus();
                //    return;
                //}

                dataGrid.UnselectAll();


                DataGridRow row2 = dataGrid.ItemContainerGenerator.ContainerFromIndex(errorRow) as DataGridRow;


                row2.IsSelected = true;


                try
                {
                    DataGridTemplateColumn tempColumn = this.dataGrid.Columns[TextIndex] as DataGridTemplateColumn;

                    FrameworkElement element1 = this.dataGrid.Columns[TextIndex].GetCellContent(this.dataGrid.Items[errorRow]);
                    TextBox ck1 = tempColumn.CellTemplate.FindName("textBoxNo", element1) as TextBox;
                    ck1.Text = "";
                    ck1.Focus();
                }
                catch (Exception)
                {

                }



            }

        }


        /// <summary>
        /// 根据行、列索引取的对应单元格对象
        /// </summary>
        /// <param name="row"></param>
        /// <param name="column"></param>
        /// <returns></returns>
        public DataGridCell GetCell(DataGrid grid, int row, int column)
        {
            DataGridRow rowContainer = GetRow(grid, row);
            if (rowContainer != null)
            {
                DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                if (presenter == null)
                {
                    grid.ScrollIntoView(rowContainer, grid.Columns[column]);
                    presenter = GetVisualChild<DataGridCellsPresenter>(rowContainer);
                }
                DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
                return cell;
            }
            return null;
        }



        private void DataGridViewToExcel(DataGrid dgv)
        {


            this.FileName = String.Format("{0}考生抽签数据-{1}-{2}", groupData.name, groupData.Interview, DateTime.Now.ToString("yyyyMMddHHmmss"));

            SaveFileDialog dlg = new SaveFileDialog
            {
                Filter = "data files (*.data)|*.data",
                FilterIndex = 0,
                RestoreDirectory = true,
                CreatePrompt = true,
                Title = "保存为data文件",
                FileName = this.FileName
            };


            if (!CheckNumber())
            { 
                return;
            }


            var exam = new EximExport
            {
                code = groupData.code
            };
            var tempSource = (List<ExamInee>)dgv.ItemsSource;

            foreach (ExamInee item in tempSource)
            {
                item.enable = false;
                if (("正常").Equals(item.result_text))
                {
                    item.result = "1";
                }else if (("违纪").Equals(item.result_text))
                {
                    item.result = "2";
                }else if (("弃考").Equals(item.result_text))
                {
                    item.result = "3";
                }

                // item.name += "";
            }
            
            this.dataGrid.ItemsSource = tempSource;

            for (var i = 0; i < tempSource.Count; i++)
            {
                try
                {
                    DataGridTemplateColumn tempColumn = this.dataGrid.Columns[TextIndex] as DataGridTemplateColumn;

                    FrameworkElement element1 = this.dataGrid.Columns[TextIndex].GetCellContent(this.dataGrid.Items[i]);
                    TextBox ck1 = tempColumn.CellTemplate.FindName("textBoxNo", element1) as TextBox;

                    ck1.IsEnabled = false;
                    ck1.IsReadOnly = true;

                }
                catch (Exception)
                {

                }

            }





            List<MiniData> listMini = new List<MiniData>();

            ///去除没有填写序号的抽签数据
            foreach (ExamInee item in tempSource)
            {
                if (!String.IsNullOrWhiteSpace(item.no))
                {
                    listMini.Add(new MiniData
                    {
                        id = item.id,
                        no = item.no,
                        result=item.result,
                        remark=""
                    });

                }
            }

            exam.data = listMini;

            var exportJson = Util.JSON.Obj2Json(exam);

            using (StreamWriter writer = new StreamWriter(Config.Document + "out" + ".json"))
            {
                writer.WriteLine(exportJson);
            }

            if (dlg.ShowDialog() == true)
            {

                Stream myStream = dlg.OpenFile();
                
                var filePath = System.IO.Path.GetDirectoryName(dlg.FileName); //-->C:\bin\files


                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                try
                {


                    var keyString = RSAHelper.PEMToXML_All(Config.public_key, false);

                    string content = RSAHelper.EncrytByPublic(keyString, exportJson);

                    sw.WriteLine(content);
                    sw.Close();
                    myStream.Close();
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.ToString());
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                    HandyControl.Controls.Growl.Success("导出成功!");
                    MakePDFFile(filePath);
                }
            }
        }
        /// <summary>
        /// 检查序号的问题
        /// </summary>
        /// <returns>Bool</returns>
        public bool CheckNumber(bool Alert = true, string[] validate =null)
        {
            //HandyControl.Controls.Growl.Clear();


            errorType = "";
            Hashtable numberHash = new Hashtable();

            var list = this.dataGrid.ItemsSource;
            List<ExamInee> examList = (List<ExamInee>)list;

            //if (String.IsNullOrEmpty(this.Actual.Text) && numberClick == false)
            //{
            //    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "请填写实到人数", WaitTime = 2 });
            //    errorType = "actual";
            //    return false;
            //}

            //if (!JSON.IsNumber(this.Actual.Text))
            //{
            //    errorType = "actual";
            //    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "实到人数应为数字!", WaitTime = 2 });
            //    return false;
            //}
            //ActualNumber = Convert.ToInt32(this.Actual.Text);

            //if (ActualNumber > this.examIneeList.Count)
            //{
            //    errorType = "actual";
            //    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "实到人数不得大于总人数!", WaitTime = 2 });
            //    return false;
            //}

            //if (ActualNumber < 0)
            //{
            //    errorType = "actual";
            //    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "实到人数不正确!", WaitTime = 2 });
            //    return false;
            //}


            if (examList == null)
            {
                return false;
            }

            //var tempNo = 0;

            for ( var i=0;i<examIneeList.Count;i++)
            {
               
                if (String.IsNullOrWhiteSpace(examIneeList[i].no))
                {
                    continue;
                }
               

                if (!JSON.IsNumber(examIneeList[i].no))
                {
                    //记录下错误的行号,方便下一步进行选中
                    errorRow = i;
                    if (Alert) { 
                          HandyControl.Controls.Growl.Warning("请输入数字!");
                    }
                    return false;
                }

                int no = Convert.ToInt32(examIneeList[i].no);


                if (0 >= no)
                {
                    //记录下错误的行号,方便下一步进行选中
                    errorRow = i;

                    if (Alert)
                    {
                        HandyControl.Controls.Growl.Warning("序号错误!");
                    }

                    return false;
                }

                //小组抽签 需要判断序号小于等于 总考生人数
                if (groupData.sort_method == "group")
                {
                    if (numberHash.ContainsKey(no))
                    {
                        //记录下错误的行号,方便下一步进行选中
                        errorRow = i;
                        if (Alert)
                        {
                            HandyControl.Controls.Growl.Warning("序号" + no + "已经存在!");
                        }
                        return false;
                    }
                    else if (maxNo < no)
                    {
                        //真实人数＜99
                        if (Convert.ToInt32(examList.Count)<maxNo)
                        {
                            //记录下错误的行号,方便下一步进行选中
                            errorRow = i;
                            if (Alert)
                            {
                                HandyControl.Controls.Growl.Warning("序号" + no + "不得超过99!");
                            }
                            return false;
                        }

                       if(Convert.ToInt32(examList.Count) < no)
                        {

                            //记录下错误的行号,方便下一步进行选中
                            errorRow = i;
                            if (Alert)
                            {
                                HandyControl.Controls.Growl.Warning("序号" + no + "大于了考试总人数!");
                            }
                            return false;
                        }
                    }
                    //else if (ActualNumber < no)
                    //{

                    //    //记录下错误的行号,方便下一步进行选中
                    //    errorRow = i;

                    //    if (Alert)
                    //    {
                    //        HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "序号" + no + "大于了应到人数!", WaitTime = 2 });
                    //    }
                    //    return false;
                    //}
                    else
                    {
                        numberHash.Add(no, "-");
                    }
                }
                else
                {
                    var arrayList = (ArrayList)JobMumberHash[examIneeList[i].job_id.ToString()];
                    //岗位抽签  需要判断序号小于等于 该岗位内考生人数
                    if (numberHash.ContainsKey(examIneeList[i].job_id + "-" + no))
                    {
                        //记录下错误的行号,方便下一步进行选中
                        errorRow = i;

                        if (Alert)
                        {
                            HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "序号" + no + "已经存在!", WaitTime = 1000 });
                        }
                        return false;
                    }
                    //else if (ActualNumber < no)
                    //{
                    //    //记录下错误的行号,方便下一步进行选中
                    //    errorRow = i;

                    //    if (Alert)
                    //    {
                    //        HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "序号" + no + "大于了应到人数!", WaitTime = 2 });
                    //    }
                    //    return false;
                    //}
                    else
                    {
                        numberHash.Add(examIneeList[i].job_id + "-" + no, "-");
                    }

                }

            }
           
            ////小组内抽签的人数个数和跳号验证
            //if (groupData.sort_method == "group")
            //{
            //    //验证序号的个数是否符合实际到场人数
            //    if (numberHash.Count!= ActualNumber && validate != IdValidate)
            //    {
            //        errorType = "actual";
            //        HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "序号个数和实际到场人数不符", WaitTime = 2 });
            //        return false;
            //    }

            //    if (numberHash.Count!= ActualNumber && validate != IdValidate)
            //    {
            //        errorType = "actual";
            //        HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "不可以跳号", WaitTime = 2 });
            //        return false;
            //    }


            //}
            //else
            //{
            //    /// 健值 职位ID  值为 no
            //    Hashtable JobNoHash = new Hashtable();
                    

            //    for (var i = 0; i < examIneeList.Count; i++)
            //    {
            //        if (String.IsNullOrEmpty(examIneeList[i].no))
            //        {
            //            continue;
            //        }

            //        if (JobNoHash.ContainsKey(examIneeList[i].job_id))
            //        {
            //            ArrayList arraylist = (ArrayList)JobNoHash[examIneeList[i].job_id.ToString()];
            //            arraylist.Add(examIneeList[i].no);
            //            JobNoHash[examIneeList[i].job_id] = arraylist;

            //        }
            //        else
            //        {
            //            JobNoHash.Add(examIneeList[i].job_id.ToString(), new ArrayList() { examIneeList[i].no.ToString() });
            //        }

            //    }
            //    //收集序号排列
            //    foreach (ArrayList arrayList in JobNoHash.Values)
            //    {
            //        tempNo = 0;
            //        foreach (string value in arrayList)
            //        {

            //            if (Convert.ToInt32(value) > ActualNumber)
            //            {
            //                if (Alert)
            //                {
            //                    errorType = "actual";
            //                    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "序号不可以大于应到人数", WaitTime = 2 });
            //                    return false;
            //                }
            //            }

                        
            //            if (validate == IdValidate)
            //            {
            //                continue;
            //            }

            //            if (tempNo == 0)
            //            {
            //                tempNo = Convert.ToInt32(value);

            //                continue;
            //            }



            //            if (Convert.ToInt32(value) != tempNo + 1)
            //            {
            //                if (Alert)
            //                {
            //                    HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "不可以跳号", WaitTime = 2 });
            //                    return false;
            //                }
            //            }

            //            tempNo = Convert.ToInt32(value);


            //        }

            //    }
            //}
             



            return true;
        }

        /// <summary>
        /// 窗体已经关闭的事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closed(object sender, EventArgs e)
        {

            this.login.Show();
            this.login.selectFile.Content = "请选择文件";
            this.login.code.Text = "";
        }

        /// <summary>
        /// 关闭中事件 可阻止关闭🚫
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            System.Windows.MessageBoxResult result= MessageBox.Show("确认关闭吗?", "", MessageBoxButton.YesNo, MessageBoxImage.Question);

            if (result == MessageBoxResult.No)
            {
                e.Cancel = true;
            }
        }


        /// <summary>
        /// 根据行索引取的行对象
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public DataGridRow GetRow(DataGrid grid, int index)
        {
            DataGridRow row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
            if (row == null)
            {
                grid.ScrollIntoView(grid.Items[index]);
                row = (DataGridRow)grid.ItemContainerGenerator.ContainerFromIndex(index);
            }
            return row;
        }

        /// <summary>
        /// 获取指定类型的子元素
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parent"></param>
        /// <returns></returns>
        private T GetVisualChild<T>(Visual parent) where T : Visual
        {
            T child = default(T);
            int numVisuals = VisualTreeHelper.GetChildrenCount(parent);
            for (int i = 0; i < numVisuals; i++)
            {
                Visual visual = (Visual)VisualTreeHelper.GetChild(parent, i);
                child = visual as T;
                if (child == null)
                {
                    child = GetVisualChild<T>(visual);
                }
                if (child != null)
                {
                    break;
                }
            }
            return child;
        }

     

        /// <summary> 
        /// 在指定时间过后执行指定的表达式 
        /// </summary> 
        /// <param name="interval">事件之间经过的时间（以毫秒为单位）</param> 
        /// <param name="action">要执行的表达式</param> 
        public  void SetTimeout(double interval, Action action)
        {
            System.Timers.Timer timer = new System.Timers.Timer(interval);
            timer.Elapsed += delegate (object sender, System.Timers.ElapsedEventArgs e)
            {
                timer.Enabled = false;
                action();
            };
            timer.Enabled = true;
        }


        private void Actual_LostFocus(object sender, RoutedEventArgs e)
        {
           
            if (!CheckNumber(true,IdValidate))
            {
                if (errorType == "actual")
                { 
                    //Actual.Text = "";
                    return;
                }

            }
        }

        public bool numberClick = false;
        private void TextBoxNo_GotFocus_1(object sender, RoutedEventArgs e)
        {
        

        }

        public void MakePDFFile(string filePath)
        {

            //创建PDF文档
            PdfDocument doc = new PdfDocument();
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, new PdfMargins(0, 0, 0, 0));

            doc.ViewerPreferences.CenterWindow = true;


            //指定页面大小
            doc.PageSettings.Size = PdfPageSize.A4;

            //将页边距设置为0 
            doc.PageSettings.Margins = new PdfMargins(0);

            //创建PdfMargins对象，指定期望设置的页边距 
            PdfMargins margins = new PdfMargins(40,10, 40, 34);

            ////在文档模板的顶部和底部应用页眉页脚模板 
            doc.Template.Top = PDFHelper.CreateHeaderTemplate(doc, new PdfMargins(40, 10, 40, 34), this.groupName.Content.ToString());
            doc.Template.Bottom = PDFHelper.CreateFooterTemplate(doc, new PdfMargins(40, 0, 40, 34), groupData);

            //自定义PdfTrueTypeFont、PdfPen实例
            PdfTrueTypeFont font = new PdfTrueTypeFont(new System.Drawing.Font("宋体", 13f), true);
            PdfPen pen = new PdfPen(System.Drawing.Color.Black);


            //在指定位置绘入表格


            var list = this.dataGrid.ItemsSource;
            List<ExamInee> examList = (List<ExamInee>)list;
            //examList= examList.Concat(examList).ToList<ExamInee>();          //保留重复项
            //examList = examList.Concat(examList).ToList<ExamInee>();          //保留重复项


         

            try
            {
                var grid = PDFHelper.Write(examList,groupData, this.groupName.Content.ToString());
                //grid.Draw(doc.Pages.Add(PdfPageSize.A4, new PdfMargins(0, 0, 0, 0)), new System.Drawing.PointF(37.5f, 35));
                grid.Draw(page, new PointF(45.5f, 39f));

                //保存到文档(我导出文件保存的位置)
                doc.SaveToFile(filePath + "\\" + this.FileName + ".pdf");
                System.Diagnostics.Process.Start(filePath + "\\" + this.FileName + ".pdf");
            }
            catch (Exception)
            {
                //HandyControl.Controls.Growl.Warning(new GrowlInfo { Message = "PDF生成失败！", WaitTime = 1000 });

            }
            

        }

        private void ComboBox_Selected(object sender, RoutedEventArgs e)
        {

        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //当前选中的索引
            //int selectIndex = comboBox.SelectedIndex;
            ////当前选中的文本
            //string str1 = comboBox.SelectedItem.ToString();

            
            //MessageBox.Show(str1);

        }

        private void Button_Print(object sender, RoutedEventArgs e)
        {
            int selectIndex = comboBox.SelectedIndex;

            if (selectIndex < 0)
            {
                comboBox.IsDropDownOpen = true;
                return;
            }


            try
            {
                String media = comboBox.SelectedItem.ToString();

                if (media.Contains("(脱机)"))
                {
                    MessageBox.Show("默认打印机脱机，请重新设置！");
                    return;
                }
                System.Windows.MessageBoxResult result = MessageBox.Show("确定使用" + media + "打印", "", MessageBoxButton.YesNo, MessageBoxImage.Question);

                if (result == MessageBoxResult.Yes)
                {

                    Assembly assembly = Assembly.GetAssembly(typeof(App));
                    Stream stream = assembly.GetManifestResourceStream("WpfApp.Resources.候考室情况记录表.pdf");
                    byte[] fileBuffer = new byte[stream.Length];
                    stream.Read(fileBuffer, 0, (int)stream.Length);


                    FileStream fielStream = new FileStream(Config.Document + @"\\候考室情况记录表.pdf", FileMode.Create, FileAccess.Write, FileShare.None);

                    fielStream.Write(fileBuffer, 0, (int)stream.Length);

                    fielStream.Close();


                    //创建PdfDocument类的对象，并加载PDF文档
                    PdfDocument doc = new PdfDocument();

                    doc.LoadFromFile(Config.Document + @"\\候考室情况记录表.pdf");

                    //指定刚刚选择的打印机
                    doc.PrintSettings.PrinterName = media;


                    //使用默认打印机打印文档所有页面
                    doc.Print();
                }

            }
            catch (Exception)
            {
                MessageBox.Show("打印出现问题");
            }


        }

        private void ComboBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
        {
           var dataContext=  (ExamInee)((ComboBox)sender).DataContext;
            
            CategoryInfo categoryInfo = (CategoryInfo)e.AddedItems[0];
            var tempSource = (List<ExamInee>)this.dataGrid.ItemsSource;

            foreach (ExamInee item in tempSource)
            {
                if (item.admission_ticket_no.Equals(dataContext.admission_ticket_no))
                {
                    item.result = categoryInfo.Value;
                }
            }

            this.dataGrid.ItemsSource = tempSource;

        }

      
    }
}
